package arr;

/**
 * @author : Rookie
 * @description : 螺旋矩阵
 * @date : 2023/8/19
 */
public class SpiralMatrix {

    public static void main(String[] args) {
        int[][] spiralMatrix = getSpiralMatrix(4);
        print(spiralMatrix);
    }

    private static int[][] getSpiralMatrix(int n) {
        int count=1,loop = n*n;
        int[][] result = new int[n][n];
        int left =0,right = n-1,top=0,bottom=n-1;
        while (count<=loop) {
            for (int i = left; i <= right; i++) {
                result[top][i] = count++;
            }
            top++;

            for (int i = top; i <= bottom; i++) {
                result[i][right] = count++;
            }
            right--;

            for (int i = right; i >=left ; i--) {
                result[bottom][i] = count++;
            }
            bottom--;

            for (int i = bottom; i >= top; i--) {
                result[i][left] = count++;
            }
            left++;
        }
        return result;
    }

    private static void print(int [][]matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}
